package com.image.controller;


import com.image.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class ImageController {

    @Autowired
    private ImageService imageService;

    @RequestMapping(value = "/get/{page}")
    @ResponseBody
    public String getImageUrl(@PathVariable int page,String url, HttpSession session) throws IOException {
        List<String> list = new ArrayList<>();
        //处理分页信息
        if(page!=99999) {
            String nowPage = (String) session.getAttribute("page");
            if (nowPage == null) {
                nowPage = "0";
            }
            page = Integer.parseInt(nowPage) + page;
            if (page < 1) {
                page = 1;
            }
            list = imageService.getImageUrl(url,page);
        }else{
            page = 1;
            list = imageService.getImageUrl(url,page);
        }

        session.setAttribute("page",page+"");
        session.setAttribute("list",list);
        session.setAttribute("url",url);
        if(list!=null){
            return "ok";
        }else{
            return "error";
        }
    }

    @RequestMapping(value = "/download")
    @ResponseBody
    public String download(String downloadUrl, HttpSession session) throws IOException {
        List<String> list = (List<String>) session.getAttribute("list");
        session.setAttribute("downloadUrl",downloadUrl);
        imageService.download(list,downloadUrl);
        return "ok";
    }
}
